package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.CheckGroupDao;
import com.itheima.dao.SetMealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetMealService;
import com.itheima.utils.QiniuUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetMealService.class)
@Transactional
public class SetMealServiceImpl implements SetMealService {
    @Autowired
    SetMealDao setMealDao;

    @Autowired
    CheckGroupDao checkGroupDao;

    @Autowired
    JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath;

    @Override
    public void add(Setmeal setMeal, Integer[] checkgroupIds) {
        setMealDao.add(setMeal);
        Integer setMealId = setMeal.getId();
        addSetMealAndGroup(setMealId, checkgroupIds);
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,setMeal.getImg());
        findById4Redis(setMealId);
//        this.generateSetMealHtml();
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Setmeal> page = setMealDao.findByCondition(queryPageBean.getQueryString());

        return new PageResult(page.getTotal(), page);
    }

    @Override
    public void del(int id) {
        Setmeal setMeal = setMealDao.findById(id);

        setMealDao.delSetMealAndGroupById(id);
        setMealDao.delSetMealById(id);
        //添加一个线程用于删除七牛云上的图片,减小等待时间
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (setMeal.getImg() != null && setMeal.getImg().length() > 0) {
                    QiniuUtils.del(setMeal.getImg());
                }
            }
        }).start();
        jedisPool.getResource().del(RedisConstant.Setmeal_detail_Data+"-"+id);
//        this.generateSetMealHtml();
    }

    @Override
    public Setmeal findById(int id) {
        //Setmeal setmeal = setMealDao.findById2(id);
//        List<CheckGroup> checkGroups= setMealDao.findGroupsBySetMealId(id);
//        for (CheckGroup checkGroup : checkGroups) {
//            checkGroup.setCheckItems(checkGroupDao.findItemsByGroupId(checkGroup.getId()));
//        }
//        setmeal.setCheckGroups(checkGroups);
        Setmeal setmeal = setMealDao.findById(id);
        return setmeal;
    }

    @Override
    public void update(Setmeal setMeal, Integer[] checkgroupIds) {
        setMealDao.update(setMeal);
        setMealDao.delSetMealAndGroupById(setMeal.getId());

        Integer setMealId = setMeal.getId();
        addSetMealAndGroup(setMealId, checkgroupIds);
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,setMeal.getImg());
        //
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (setMeal.getImg() != null && setMeal.getImg().length() > 0) {
                    QiniuUtils.del(setMeal.getImg());
                }
            }
        });
        findById4Redis(setMealId);
//        this.generateSetMealHtml();
    }

    @Override
    public PageResult findPage4Redis(QueryPageBean queryPageBean) {
        Jedis jedis = jedisPool.getResource();
        String setmeal = jedis.get(RedisConstant.Setmeal_Data);
        if (setmeal==null||setmeal.length()==0){
            PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
            Page<Setmeal> page = setMealDao.findByCondition(queryPageBean.getQueryString());
            if (page==null){
                jedis.setex(RedisConstant.Setmeal_Data,60,"");
                setmeal=jedis.get(RedisConstant.Setmeal_Data);
                return JSONObject.parseObject(setmeal,PageResult.class);
            }
            PageResult pageResult=new PageResult(page.getTotal(), page);
            String pageResult2Json = JSON.toJSON(pageResult).toString();
            jedis.set(RedisConstant.Setmeal_Data,pageResult2Json);
            setmeal=jedisPool.getResource().get(RedisConstant.Setmeal_Data);
        }
        jedis.close();
        return JSONObject.parseObject(setmeal,PageResult.class);
    }

    @Override
    public Setmeal findById4Redis(int id) {
        Jedis jedis = jedisPool.getResource();
        String setmeal_detail = jedis.get(RedisConstant.Setmeal_detail_Data+"-"+id);
        if (setmeal_detail==null||setmeal_detail.length()==0){
            Setmeal setmeal = setMealDao.findById(id);
            if (setmeal==null){
                jedis.setex(RedisConstant.Setmeal_detail_Data+"-"+id,60,"");
                setmeal_detail=jedis.get(RedisConstant.Setmeal_detail_Data+"-"+id);
                return JSONObject.parseObject(setmeal_detail,Setmeal.class);
            }
            String setmeal2Json=JSON.toJSON(setmeal).toString();
            jedis.set(RedisConstant.Setmeal_detail_Data+"-"+id,setmeal2Json);
            setmeal_detail=jedis.get(RedisConstant.Setmeal_detail_Data+"-"+id);
        }
        jedis.close();
        return JSONObject.parseObject(setmeal_detail,Setmeal.class);
    }


    private void addSetMealAndGroup(Integer setMealId, Integer[] checkgroupIds) {
        HashMap<String, Integer> map = new HashMap<>();
        for (Integer checkgroupId : checkgroupIds) {
            map.put("setMealId", setMealId);
            map.put("checkgroupId", checkgroupId);
            setMealDao.addSetMealAndGroup(map);
        }
    }

    private void generateSetMealDetailHtml(List<Setmeal> setmealList){
        for (Setmeal setmeal : setmealList) {
            Map map = new HashMap<>();
            map.put("setmeal", setmeal);
            String templateName = "setmeal_detail.ftl";
            String fileName = "m_setmeal_detail.html_" + setmeal.getId() + ".html";
            generateStaticHtml(templateName, fileName, map);
        }
    }

    private void generateSetMealHtml(){
        List<Setmeal> setmealList = setMealDao.findByCondition(null);
        Map map = new HashMap();
        map.put("setmealList", setmealList);
        String templateName = "setmeal.ftl";
        String fileName = "m_setmeal.html";
        generateStaticHtml(templateName, fileName, map);
        generateSetMealDetailHtml(setmealList);
    }


    private void generateStaticHtml(String templateName, String fileName, Map map) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            out = new FileWriter(new File(outPutPath + fileName));
            template.process(map, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
